<?php

namespace App\Kuafu\Wechat\Controller\Pos;

use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Wechat\Service\WechatSendMessageService;
use App\Support\MQTT;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;

class WechatController extends BaseController
{
    public function callNumberSendMessage(Request $request)
    {
        $orderId    = (int)$request->orderId;
        $platformId = $request->platformId ?: 1;
        $field      = ['shopId', 'orderId', 'serialNum', 'createdAt', 'platformId', 'sourceType'];
        $orderInfo  = OrderService::getOrderFieldByOrderId($orderId, $field, $this->shopId);

        // MQTT 推送叫号信息
        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_ORDER_CALL_NUM, [
            'timestamp' => time(),
            'orderId'   => (string)$orderId,
            'serialNum' => $orderInfo['serialNum'],
        ], MQTT::MQTT_CLIENT_CONNECT_SHOP);


        if (!empty($orderInfo['platformId'] && $orderInfo['sourceType'] == CodeEnum::SOURCE_TYPE_MINI)) {
            //通过unionid查询用户openid
            $userInfoByUnionid   = CustomerPlatformService::getUserInfoByUnionid($orderInfo['platformId'], $platformId,
                ['openId']);
            $openid              = $userInfoByUnionid['openId'];
            $shopId              = $orderInfo['shopId'];
            $shopInfo            = ShopService::getShopInfo($shopId);
            $serialNum           = str_pad($orderInfo['serialNum'], ShopCodeEnum::CODE_TEXT[ShopCodeEnum::LEADING_ZERO],
                "0", STR_PAD_LEFT);
            $name                = $shopInfo['name'];
            $address             = mb_substr($shopInfo['address'], 0, 19, 'utf-8');
            $time                = $orderInfo['createdAt'];
            $time                = date("Y年m月d日 H:i", strtotime($time));
            $payOrderSendMessage = WechatSendMessageService::callNumberSendMessage($serialNum, $name, $address, $time,
                $openid, $orderId, $shopInfo['id']);
            return $this->success($payOrderSendMessage);
        }


        return $this->success();
    }
}

